package com.example.votingsystem.service;

import com.example.votingsystem.entity.VoteTopic;
import com.example.votingsystem.entity.VoteOption;
import com.example.votingsystem.entity.VoteRecord;
import com.example.votingsystem.repository.VoteTopicRepository;
import com.example.votingsystem.repository.VoteOptionRepository;
import com.example.votingsystem.repository.VoteRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class VoteService {

    @Autowired
    private VoteTopicRepository voteTopicRepository;

    @Autowired
    private VoteOptionRepository voteOptionRepository;

    @Autowired
    private VoteRecordRepository voteRecordRepository;

    public List<VoteTopic> getActiveVoteTopics() {
        return voteTopicRepository.findByIsActiveTrue();
    }

    public List<VoteTopic> getUpcomingVotes() {
        return voteTopicRepository.findUpcomingVotes(LocalDateTime.now());
    }

    public List<VoteTopic> getPopularVotes() {
        return voteTopicRepository.findPopularVotes();
    }

    @Transactional
    public VoteRecord castVote(Long userId, Long topicId, Long optionId) {
        VoteTopic topic = voteTopicRepository.findById(topicId)
                .orElseThrow(() -> new RuntimeException("Vote topic not found"));

        if (!topic.isActive()) {
            throw new RuntimeException("This vote topic is not active");
        }

        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(topic.getStartTime()) || now.isAfter(topic.getEndTime())) {
            throw new RuntimeException("Voting is not allowed at this time");
        }

        if (voteRecordRepository.hasUserVotedToday(userId, topicId)) {
            throw new RuntimeException("You have already voted on this topic today");
        }

        VoteOption option = voteOptionRepository.findById(optionId)
                .orElseThrow(() -> new RuntimeException("Vote option not found"));

        VoteRecord voteRecord = new VoteRecord();
        voteRecord.setUserId(userId);
        voteRecord.setVoteTopic(topic);
        voteRecord.setVoteOption(option);

        option.setVoteCount(option.getVoteCount() + 1);
        voteOptionRepository.save(option);

        return voteRecordRepository.save(voteRecord);
    }

    public List<VoteRecord> getUserVoteHistory(Long userId) {
        return voteRecordRepository.findByUserId(userId);
    }

    public VoteTopic createVoteTopic(VoteTopic voteTopic) {
        return voteTopicRepository.save(voteTopic);
    }

    public VoteOption addVoteOption(VoteOption voteOption) {
        return voteOptionRepository.save(voteOption);
    }
}
